package com.codi.api.xxljob;

import com.codi.base.cache.CacheUtil;
import com.codi.base.exception.BaseAppException;
import com.codi.base.util.ListUtil;
import com.codi.bus.constant.CacheKeyConst;
import com.codi.bus.core.domain.FundInfo;
import com.codi.bus.core.service.FundDetailService;
import com.codi.bus.core.service.FundInfoService;
import com.codi.fundData.domain.FundDetail;
import com.codi.fundData.domain.FundRating;
import com.codi.fundData.service.FundRatingService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * @author lvgo
 * @version 1.0
 * @Description: 刷新基金评级
 * 0 0 2 ? * 1,3
 * @date 18-6-29 下午5:57
 */
@Slf4j
@Component
@JobHandler("fundRatingHandler")
public class FundRatingHandler extends IJobHandler {
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private FundInfoService fundInfoService;
    @Resource
    private FundDetailService fundDetailService;
    @Resource
    private FundRatingService fundRatingService;

    @Override
    public ReturnT<String> execute(String param) throws Exception {

        Set<String> keys = redisTemplate.keys(CacheKeyConst.MF_FUNDRATING + ":*");
        if (keys != null && !keys.isEmpty()) {
            log.debug("fund type keys length={}", keys.size());
            redisTemplate.delete(keys);
        }
        int pageSize = 100, pageIndex = 1, delay = 2 * 1000;
        while (true) {
            log.debug("loading fund pageIndex={}", pageIndex);
            List<FundInfo> funds = fundInfoService.queryPage(pageSize, pageIndex);
            if (ListUtil.isEmpty(funds)) {
                break;
            }
            for (FundInfo fund : funds) {
                FundDetail fundDetail = fundDetailService.getFundDetail(fund.getFundCode());
                if (fundDetail != null) {
                    try {
                        int innerCode = fundDetail.getInnerCode();
                        FundRating fundRating = fundRatingService.queryFundRatingByInnerCode(innerCode);
                        String key = CacheUtil.getKey(CacheKeyConst.MF_FUNDRATING, innerCode);
                        CacheUtil.setStrObj(redisTemplate, key, fundRating);
                    } catch (BaseAppException e) {
                        log.error("fail to query rating", e);
                    }
                }
            }
            if (funds.size() < pageSize) {
                break;
            }
            pageIndex++;
            try {
                Thread.sleep(delay);
            } catch (InterruptedException e) {
                log.error("fail to sleep", e);
            }
        }
        return SUCCESS;
    }
}
